import axios from "axios";
import router from '../router'
import storageUtil from '../utils/localstorage'
import Loading from 'element-plus/lib/components/loading'
import ElMessage from 'element-plus/lib/components/message'

let config = {
  baseURL:'',
  timeout:10000
}
//创建实例
let instance = axios.create(config)
let loading={};
//请求拦截器
instance.interceptors.request.use(config=>{
  // console.log(req);
  let uid = storageUtil.get("uid");
  let token = storageUtil.get("token");
  if(uid){
    config.headers.uid = uid;
    config.headers.token = token;
    // config.headers={"uid":uid,"token":token};
  }
  loading = Loading.service({fullscreen:true,text:"数据加载中..."})//显示加载效果
  return config;//拦截器里一定要返回config, 不然请求无法发送出去。
})
//响应拦截器
instance.interceptors.response.use(resp =>{
  loading.close();
  if(resp.status === 200){
    let data = resp.data;
    if(data.code === 2){
      router.push("/login")
    }else if(data.code === 0) {
      return data.result;
    }else{
      //弹出框显示后台返回的错误信息
      ElMessage({showClose:true,message:data.msg,type:'warning'});
    }
  }
},error=>{
  //请求发生异常
  loading.close();
  return Promise.reject(error);
})

let http = {
  install(app){
    app.config.globalProperties.$axios = instance;
  }
}
export default http;
